package com.example.carefree_server.controller.c_loginController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.example.carefree_server.utils.ResponseCode;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static com.example.carefree_server.utils.ResponseCode.responseCode;

@RestController
@RequestMapping("/verify/code")
public class VerifyCodeController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //获取扭曲干扰的验证码
    @GetMapping("/createShearCaptcha")
    public void getShearCaptcha(HttpServletResponse response)
    {

        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 50,4,3);
        //设置背景颜色
        shearCaptcha.setBackground(new Color(249, 251, 220));

        // 创建一个包含26个英文字母（大小写）的字符串
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        // 生成一个长度为4的随机字符串，只包含上面指定的字符
        //生成四位验证码
        String code = RandomUtil.randomString(chars,4);

        //生成验证码图片
        Image image = shearCaptcha.createImage(code);
        //返回验证码信息

        code = code.toLowerCase();
        ValueOperations<String, String> Operations = stringRedisTemplate.opsForValue();//创建redis容器
        Operations.set(code,code,10, TimeUnit.MINUTES);//重载,设置验证码失效时长为10分钟
        responseCode(response, code, image);
    }

}
